import { useCssVar } from '@vueuse/core'
import type { Ref } from 'vue'

export function fetchElementUIThemeCluster(theme: string) {
  const tintColor = (color: string, tint: number) => {
    let red: string | number = Number.parseInt(color.slice(0, 2), 16)
    let green: string | number = Number.parseInt(color.slice(2, 4), 16)
    let blue: string | number = Number.parseInt(color.slice(4, 6), 16)

    if (tint === 0) {
      // 生成rgb格式
      return `rgb(${[red, green, blue].join(',')})`
    }
    else {
      red += Math.round(tint * (255 - red))
      green += Math.round(tint * (255 - green))
      blue += Math.round(tint * (255 - blue))

      red = red.toString(16).padStart(2, '0')
      green = green.toString(16).padStart(2, '0')
      blue = blue.toString(16).padStart(2, '0')

      return `#${red}${green}${blue}`
    }
  }

  const shadeColor = (color: string, shade: number) => {
    let red: string | number = Number.parseInt(color.slice(0, 2), 16)
    let green: string | number = Number.parseInt(color.slice(2, 4), 16)
    let blue: string | number = Number.parseInt(color.slice(4, 6), 16)

    red = Math.round((1 - shade) * red)
    green = Math.round((1 - shade) * green)
    blue = Math.round((1 - shade) * blue)

    red = red.toString(16).padStart(2, '0')
    green = green.toString(16).padStart(2, '0')
    blue = blue.toString(16).padStart(2, '0')

    return `#${red}${green}${blue}`
  }

  const clusters = [`#${theme}`]
  for (let i = 0; i <= 9; i++) {
    clusters.push(tintColor(theme, Number((i / 10).toFixed(2))))
  }
  clusters.push(shadeColor(theme, 0.1))
  return clusters
}

export function updateElementUITheme(
  color: string,
  type: 'primary' | 'success' | 'danger' | 'error' | 'info' = 'primary',
  themeType: 'dark' | 'light' = 'light',
) {
  const themeIndex = themeType === 'light' ? [0, 2, 3, 5, 7, 8, 9] : []
  const handlerThemeCluster: Record<string, Ref<string>> = {}
  // 得到一系列 主题色颜色 (我们需要的颜色 '产出')
  const themeCluster = fetchElementUIThemeCluster(color.replace('#', ''))

  themeIndex.forEach((index) => {
    handlerThemeCluster[index] = useCssVar(
      index === 0
        ? `--el-color-${type}`
        : index === 2
          ? `--el-color-${type}-${
            themeType === 'dark' ? 'light' : 'dark'
          }-${index}`
          : `--el-color-${type}-${themeType}-${index}`,
    )
  })
  for (const index in handlerThemeCluster) {
    const target = handlerThemeCluster[index]
    target!.value
      = index === '2' ? themeCluster.at(-1)! : themeCluster[index as any]!
  }
  return handlerThemeCluster
}
